package edu.uni.dormitory.controller;

import com.github.pagehelper.PageInfo;
import edu.uni.auth.bean.User;
import edu.uni.auth.service.AuthService;
import edu.uni.bean.Result;
import edu.uni.bean.ResultType;
import edu.uni.dormitory.bean.LiveArea;
import edu.uni.dormitory.bean.LiveBed;
import edu.uni.dormitory.bean.StudentBed;
import edu.uni.dormitory.dto.Query;
import edu.uni.dormitory.globalbean.BedVo;
import edu.uni.dormitory.service.AreaService;
import edu.uni.dormitory.service.BedService;
import edu.uni.userBaseInfo1.bean.Employee;
import edu.uni.userBaseInfo1.service.EmployeeService;
import edu.uni.utils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static edu.uni.bean.ResultType.Success;
/**
 * @author 陈楚城
 * @create 2019.05.02
 * @function 床位
 */
@Api(description = "床位信息模块")
@Controller
@RequestMapping("json/dorm/bed")
public class BedController{
    @Autowired
    private BedService bedService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private RedisCache cache;
    @Autowired
    private AuthService authService;
    @Autowired
    private EmployeeService employeeService;
    /**
     * 内部类，专门用来管理每个方法所对应缓存的名称。
     */
    static class CacheNameHelper{
        // dorm_bed_{liveRoomId}
        private static final String Receive_CacheNamePrefix = "dorm_bed_";
        // dorm_bed_Alist_{宿舍区id}
        private static final String List_A_CacheNamePrefix = "dorm_bed_Alist_";
        // dorm_bed_listByAId_{宿舍区id}_{页码}
        private static final String ListByAId_CacheNamePrefix = "dorm_bed_listByAId_";
    }

    /**
     * 通过宿舍id获取床位记录
     */
    @ApiOperation(value = "根据宿舍id获取床位信息", notes = "未测试")
    @GetMapping("listByRoomId/{liveRoomId}")
    public void getBedListByliveRoomId(@PathVariable("liveRoomId")long liveRoomId, HttpSession session, HttpServletResponse response)throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //String cacheName =CacheNameHelper.Receive_CacheNamePrefix+liveRoomId;
       // String json = cache.get(cacheName);
        String json=null;
        if(json==null){
            List<BedVo> list=bedService.selectLiveBedByRoomId(liveRoomId);
            List<BedVo> list0=new ArrayList<BedVo>();
            List<BedVo> list1=new ArrayList<BedVo>();
            for(BedVo BedVoList :list){
                if(BedVoList.getStatus()==0){
                    BedVoList.setState("已住");
                    list0.add(BedVoList);
                }else {
                    BedVoList.setState("未住");
                    list1.add(BedVoList);
                } if(BedVoList.getType()==0){

                    BedVoList.setType1("男");

                }else
                    BedVoList.setType1("女");

            }
            json = Result.build(ResultType.Success).appendData("list0", list0).appendData("list1",list1).convertIntoJSON();
            if(list != null){
                //cache.set(cacheName, json);
            }
        }
        response.getWriter().write(json);
        //return Result.build(Success);
    }
    /**
     * 通过宿舍区id获取床位记录
     */
    @ApiOperation(value = "根据宿舍区id获取床位信息", notes = "未测试")
    @GetMapping("listAreaId")
    public void getBedListByareaId(  HttpSession session,HttpServletResponse response)throws IOException{
        response.setContentType("application/json;charset=utf-8");
        //String cacheName =CacheNameHelper.List_A_CacheNamePrefix +areaId;
       // String json = cache.get(cacheName);
        //long employeeId=4;//登录人身份
        User user = authService.getUser();
        List<Employee> employees=employeeService.selectByUserId(user.getId());
        long employeeId=employees.get(0).getId();
        long areaId=areaService.selectAreaIdByEid(employeeId).getAreaId();
        String json=null;
        if(json == null){
            List<BedVo> list=bedService.selectLiveBedByAreaId(areaId);

            List<BedVo> list0=new ArrayList<BedVo>();
            List<BedVo> list1=new ArrayList<BedVo>();
            for(BedVo BedVoList :list){
                if(BedVoList.getStatus()==0){
                    BedVoList.setState("已住");
                    list0.add(BedVoList);
                }else {
                    BedVoList.setState("未住");
                    list1.add(BedVoList);
                }
                if(BedVoList.getType()==0){

                    BedVoList.setType1("男");

                }else
                    BedVoList.setType1("女");


            }
            json = Result.build(ResultType.Success).appendData("list0", list0).appendData("list1",list1).convertIntoJSON();
            if(list != null){
                //cache.set(cacheName, json);
            }

        }
        response.getWriter().write(json);
       // return Result.build(Success);
    }
    /**
     * 根据宿舍区id和页码来分页查询床位信息
     */
    @ApiOperation(value = "根据宿舍区id和页码来分页查询床位信息", notes = "未测试")
    @GetMapping(value = "listAreaId/{areaId}/{pageNum}")
    public void listByAid(@PathVariable long areaId,
                          @PathVariable Integer pageNum,
                          HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
       // String cacheName = CacheNameHelper.ListByAId_CacheNamePrefix + areaId + "_" + pageNum;
        //String json = cache.get(cacheName);
        String json=null;
        if(json == null){
            PageInfo<BedVo> pageInfo0=bedService.selectPageByAreaIdYes(pageNum,areaId);//有人床位
            PageInfo<BedVo> pageInfo1=bedService.selectPageByAreaIdNo(pageNum,areaId);//无人床位


            json = Result.build(ResultType.Success).appendData("pageInfo0", pageInfo0).appendData("pageInfo1", pageInfo1).convertIntoJSON();
            if(pageInfo0 != null) {
                //cache.set(cacheName, json);
            }
        }
        response.getWriter().write(json);
        // return  Result.build(Success);
    }



    /**
     * 新增床位
     */
    @ApiOperation(value = "新增床位", notes = "未测试")
    @PostMapping()
    public Result addBed(long areaId,LiveBed liveBed, HttpSession session){
        if(liveBed !=null){
            boolean success =bedService.update(liveBed);
            if(success){
                //cache.deleteByPaterm(CacheNameHelper.Receive_CacheNamePrefix+ "*");
                cache.deleteByPaterm(CacheNameHelper.List_A_CacheNamePrefix+ "*");
                cache.deleteByPaterm(CacheNameHelper.ListByAId_CacheNamePrefix+ "*");
                return Result.build(ResultType.Success);
            }else{
                return Result.build(ResultType.Failed);
            }

        }
        return Result.build(ResultType.ParamError);
        //return Result.build(Success);
    }
    /**
     * 删除宿舍床位
     */
    @ApiOperation(value = "删除床位信息", notes = "未测试")
    @DeleteMapping("{id}")
    public Result removeBed(@PathVariable("id")long id,HttpSession session){
        boolean success = bedService.delete(id);
        if(success){
            cache.deleteByPaterm(CacheNameHelper.Receive_CacheNamePrefix + "*");
            cache.deleteByPaterm(CacheNameHelper.ListByAId_CacheNamePrefix + "*");
            cache.deleteByPaterm(CacheNameHelper.List_A_CacheNamePrefix + "*");
            return Result.build(ResultType.Success);
        }else{
            return Result.build(ResultType.Failed);
        }
       // return Result.build(Success);
    }
    /**
     * 修改宿舍区信息
     */
    @ApiOperation(value = "修改床位信息", notes = "")
    @PutMapping()
    @ResponseBody
    public Result updateBed(@RequestBody(required = false) LiveBed liveBed){

        if(liveBed != null && liveBed.getId() != null){
            boolean success = bedService.update(liveBed);
            if(success){
                cache.deleteByPaterm(CacheNameHelper.Receive_CacheNamePrefix + "*");
                cache.deleteByPaterm(CacheNameHelper.ListByAId_CacheNamePrefix + "*");
                cache.deleteByPaterm(CacheNameHelper.List_A_CacheNamePrefix + "*");
                return Result.build(ResultType.Success);
            }else{
                return Result.build(ResultType.Failed);
            }
        }
        return Result.build(ResultType.ParamError);
    }
}
